package com.itheima.stock.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @ClassName TaskExecutePool
 * @Author Carithly
 * @Description 自定义采集数据线程池
 * @Date 2022/10/24 11:55
 * @Version 1.0.0
 * @Entity com.itheima.stock.config
 */
@Configuration
@Slf4j
public class TaskExecutePool {
    private TaskThreadPoolInfo taskThreadPoolInfo;
    public TaskExecutePool (TaskThreadPoolInfo taskThreadPoolInfo){
        this.taskThreadPoolInfo =taskThreadPoolInfo;
    }
    /**
     * 创建spring任务线程对象 放入spring容器中
     * @return
     */
    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor(){
        //构建线程池对象
        ThreadPoolTaskExecutor tPTE = new ThreadPoolTaskExecutor();
        //核心线程数：核心线程数（获取硬件）：线程池创建时候初始化的线程数
        tPTE.setCorePoolSize(taskThreadPoolInfo.getCorePoolSize());
//最大线程数：只有在缓冲队列满了之后才会申请超过核心线程数的线程
        tPTE.setMaxPoolSize(taskThreadPoolInfo.getMaxPoolSize());
        //缓冲队列：用来缓冲执行任务的队列
        tPTE.setQueueCapacity(taskThreadPoolInfo.getQueueCapacity());
        //允许线程的空闲时间：当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
        tPTE.setKeepAliveSeconds(taskThreadPoolInfo.getKeepAliveSeconds());
        //线程名称前缀
        tPTE.setThreadNamePrefix("StockThread-");
        //设置拒绝策略
        tPTE.setRejectedExecutionHandler((runnable, executor)->{
            log.info("股票任务出现异常:发送邮件");
        });
        //参数初始化
        tPTE.initialize();
        return tPTE;
    }
    /**
     * 自定义线程拒绝策略
     * @return
     */
    @Bean
    public RejectedExecutionHandler rejectedExecutionHandler(){
        RejectedExecutionHandler errorHandler = new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable runnable, ThreadPoolExecutor executor) {
                //TODO 可自定义Runable实现类，传入参数，做到不同任务，不同处理
                log.info("股票任务出现异常:发送邮件");
            }
        };
        return errorHandler;
    }
}
